/**
 * 页面跳转优化工具
 * 提供预加载、loading状态管理、跳转动画等功能
 */

/**
 * 优化的页面跳转函数
 * @param {Object} options 跳转选项
 * @param {string} options.url 目标页面URL
 * @param {string} options.method 跳转方法 navigateTo|redirectTo|reLaunch|switchTab
 * @param {boolean} options.showLoading 是否显示loading
 * @param {string} options.loadingText loading文本
 * @param {Function} options.beforeNavigate 跳转前回调
 * @param {Function} options.afterNavigate 跳转后回调
 */
const optimizedNavigate = (options = {}) => {
  const {
    url,
    method = 'navigateTo',
    showLoading = true,
    loadingText = '页面跳转中...',
    beforeNavigate,
    afterNavigate
  } = options;

  return new Promise((resolve, reject) => {
    // 执行跳转前回调
    if (beforeNavigate && typeof beforeNavigate === 'function') {
      beforeNavigate();
    }

    // 显示loading
    if (showLoading) {
      wx.showLoading({
        title: loadingText,
        mask: true
      });
    }

    // 延迟执行跳转，让loading先显示
    setTimeout(() => {
      const navigateFunction = wx[method];
      
      if (!navigateFunction) {
        wx.hideLoading();
        reject(new Error(`不支持的跳转方法: ${method}`));
        return;
      }

      navigateFunction({
        url,
        success: (res) => {
          wx.hideLoading();
          
          // 执行跳转后回调
          if (afterNavigate && typeof afterNavigate === 'function') {
            afterNavigate();
          }
          
          resolve(res);
        },
        fail: (err) => {
          wx.hideLoading();
    
          
          // 显示错误提示
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none',
            duration: 2000
          });
          
          reject(err);
        }
      });
    }, 50); // 50ms延迟，让loading先显示
  });
};

/**
 * 预加载页面数据
 * @param {string} pageUrl 页面URL
 * @param {Object} params 预加载参数
 */
const preloadPageData = async (pageUrl, params = {}) => {
  
  // 根据页面URL决定预加载策略
  switch (true) {
    case pageUrl.includes('piecework-today'):
      return await preloadPieceworkTodayData(params);
    case pageUrl.includes('salary-query'):
      return await preloadSalaryQueryData(params);
    default:
      return null;
  }
};

/**
 * 预加载计件今日数据
 */
const preloadPieceworkTodayData = async (params) => {
  try {
    const { date, employeeAccount } = params;
    if (!date || !employeeAccount) return null;
    
    // 这里可以提前调用API获取数据
    const { getTodayEntryList } = require('./piecework-entry-api.js');
    const result = await getTodayEntryList(date, employeeAccount);
    
    if (result.message == "操作成功") {
      return result.data;
    }
  } catch (error) {
    
  }
  return null;
};

/**
 * 预加载工资查询数据
 */
const preloadSalaryQueryData = async (params) => {
  try {
    // 这里可以提前调用工资查询相关API
    // 具体实现根据需要添加
  } catch (error) {
    
  }
  return null;
};

/**
 * 带预加载的页面跳转
 * @param {Object} options 跳转选项
 */
const navigateWithPreload = async (options = {}) => {
  const { url, preloadParams, ...navigateOptions } = options;
  
  try {
    // 并行执行预加载和页面跳转
    const [_, preloadData] = await Promise.all([
      optimizedNavigate({ url, ...navigateOptions }),
      preloadPageData(url, preloadParams)
    ]);
    
    // 如果有预加载数据，可以通过事件或storage传递给目标页面
    if (preloadData) {
      const cacheKey = `preload_${url.split('?')[0]}_${Date.now()}`;
      wx.setStorageSync(cacheKey, {
        data: preloadData,
        timestamp: Date.now()
      });
      
      // 通知目标页面有预加载数据
      wx.eventBus && wx.eventBus.emit('preload-data-ready', {
        url,
        cacheKey
      });
    }
    
  } catch (error) {
    
    throw error;
  }
};

/**
 * 快速跳转函数集合
 */
const quickNavigate = {
  // 跳转到计件今日页面
  toPieceworkToday: (date, from) => {
    const url = `/pages/piecework-today/piecework-today?date=${date}&from=${from}`;
    return optimizedNavigate({
      url,
      loadingText: '加载数据中...'
    });
  },
  
  // 跳转到工资查询页面
  toSalaryQuery: () => {
    return optimizedNavigate({
      url: '/pages/salary-query/salary-query',
      loadingText: '正在跳转...'
    });
  },
  
  // 跳转到工作台
  toWorkbench: () => {
    return optimizedNavigate({
      url: '/pages/workbench/workbench',
      method: 'switchTab',
      loadingText: '返回工作台...'
    });
  }
};

/**
 * 页面性能监控
 */
const performanceMonitor = {
  startTime: null,
  
  start(pageName) {
    this.startTime = Date.now();
    
  },
  
  end(pageName) {
    if (this.startTime) {
      const duration = Date.now() - this.startTime;

      
      // 记录性能数据（可以上报到服务器）
      
      if (duration > 3000) {
  
      }
      
      this.startTime = null;
    }
  }
};

module.exports = {
  optimizedNavigate,
  preloadPageData,
  navigateWithPreload,
  quickNavigate,
  performanceMonitor
};